import { Form, Input, Modal } from "antd";
import type { IAction } from "../../../types/modal";
import { useImperativeHandle, useState } from "react";
import type { Role } from "../../../types/api";
import api from "../../../api";
import { message } from "../../../utils/AntdGlobal";

export default function CreateRole(props: any) {
    const [form] = Form.useForm()
    const [action, setAction] = useState<IAction>('create')
    const [visible, setVisible] = useState(false)

    useImperativeHandle(props.ref, () => {
        return { open }
    })
    const open = (type: IAction, data?: Role.EditParams | { parentId: string }) => {
        setVisible(true)
        setAction(type)
        if (data) {
            form.setFieldsValue(data)
        }
    }

    const handleSubmit = async () => {
        const valid = await form.validateFields()
        if (valid) {
            if (action === 'create') {
                await api.createRole(form.getFieldsValue())
                message.success("创建成功")
            } else {
                await api.editRole(form.getFieldsValue())
                message.success("修改成功")
            }
            handleCancel()
            props.update()
        }
    }
    const handleCancel = () => {
        setVisible(false)
        form.resetFields()
    }
    return (
        <>
            <Modal
                title={action === 'create' ? '创建角色' : '编辑角色'}
                width={600}
                open={visible}
                okText="确定"
                cancelText="取消"
                onOk={handleSubmit}
                onCancel={handleCancel}
            >
                <Form
                    form={form}
                    labelCol={{ span: 4 }}
                    labelAlign="right"
                >
                    <Form.Item name="_id" hidden><Input /></Form.Item>
                    <Form.Item label="角色名称" name="roleName" rules={[{ required: true, message: '请输入角色名称' }]}>
                        <Input placeholder="请输入角色名称" />
                    </Form.Item>
                    <Form.Item label="备注" name="remark">
                        <Input.TextArea placeholder="请输入备注" />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    )
}